import 'package:flutter/material.dart';
import 'package:flutter_app_05/utils/MyTheme.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../widget/calculator_item.dart';
import '../utils/image_helper.dart';
import '../utils/calculator.dart';
import '../utils/widget_util.dart';

///计算器
class CalculatorPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _CalculatorPageState();
  }
}

class _CalculatorPageState extends State<CalculatorPage>
    with TickerProviderStateMixin {
  String text1 = "";
  String text2 = "";
  String unitUp = "";
  String unitResult = "";
  String unitDown = "";
  bool isNew = false;
  AnimationController controller;
  Animation<double> animation;
  double top1 = 100;
  double top2 = 150;
  double font1 = 30;
  double font2 = 20;
  bool hideFont2 = false;
  Calculator calculator = Calculator();
  double fontLevel1, fontLevel2;
  double currentFontLevel;
  List<String> _values = ["标准", "体积", "重量", "热量", "压力"];
  int index = 0;
  String _dvalue;
  BuildContext mContext;

  @override
  void initState() {
    super.initState();
    _dvalue = _values.first;
    controller = AnimationController(
        vsync: this, duration: const Duration(milliseconds: 300));
    CurvedAnimation easy =
        CurvedAnimation(parent: controller, curve: Curves.easeIn);
    animation = Tween(begin: 0.0, end: 1.0).animate(easy)
      ..addListener(() {
        double v = animation.value * 50;
        double level = text2.length > 15 ? fontLevel2 : fontLevel1;
        double f = animation.value * (level - fontLevel2);
        top1 = 100 - v;
        top2 = 150 - v;
        font2 = fontLevel2 + f;

        setState(() {});
      })
      ..addStatusListener((status) {
        if (status == AnimationStatus.completed) {
          top1 = 100;
          top2 = 150;
          hideFont2 = true;

          calculator.reset(text2);
          print(text1 + "aaaaaaaaaaaaaa");
          text2 = "";
          setState(() {});
          controller.reset();
        } else if (status == AnimationStatus.forward) {
          setState(() {
            hideFont2 = false;
          });
        }
      });
  }

  void addText(text) {
    calculator.addText(text);
    var value = calculator.calculate();
    text1 = calculator.expressionText();

    text2 = value;
    hideFont2 = false;
    currentFontLevel = text1.length > 15 ? fontLevel2 : fontLevel1;
    font1 = currentFontLevel;
    setState(() {});
  }

  /**
   * 0 :L => m³
   * 1 :m³=> L
   * */
  void volum() async {
    text1 = text2==""?text1:text2;
    SharedPreferences prefs = await SharedPreferences.getInstance();
    int a = prefs.get("tiji") ?? 0;
    double b;
    if (text1 != "") {
       b= double.parse(text1);
    } else {
      this.unitResult = "";
      b=0.0;
    }
    if (a == 0) {
      this.unitDown = "L";
      this.unitUp = "m³";
      this.unitResult = (b / 1000).toString();
    } else {
      this.unitUp = "L";
      this.unitDown = "m³";
      this.unitResult = (b * 1000).toString();
    }
  }

  /**
   * 0:t => kg
   * 1:kg => t
   * */
  void weight() async {
    text1 = text2==""?text1:text2;

    if (text1 != "") {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int a = prefs.get("weights") ?? 0;
      double b = double.parse(text1);
      if (a == 0) {
        this.unitDown = "t";
        this.unitUp = "kg";
        this.unitResult = (b * 1000).toString();
      } else {
        this.unitDown = "kg";
        this.unitUp = "t";
        this.unitResult = (b / 1000).toString();
      }
      setState(() {});
    } else {
      this.unitResult = "";
    }
  }

  /**
   *0:khw => gj
   * 1:gj=>khw
   * */
  void hot() async {
    text1 = text2==""?text1:text2;

    if (text1 != "") {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int a = prefs.get("hot") ?? 0;
      double b = double.parse(text1);
      if (a == 0) {
        this.unitDown = "khw";
        this.unitUp = "GJ";
        this.unitResult = (b * (3.6 / 1000)).toString();
      } else if (a == 1) {
        this.unitDown = "GJ";
        this.unitUp = "khw";
        this.unitResult = (b / (3.6 / 1000)).toString();
      }
    } else {
      this.unitResult = "";
    }
  }

  /**
   * 0: 水柱=>kpa
   * 1: kpa=>水柱
   * */
  void press() async {
    text1 = text2==""?text1:text2;

    if (text1 != "") {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int a = prefs.get("yali") ?? 0;
      double b = double.parse(text1);
      if (a == 0) {
        this.unitDown = "水柱";
        this.unitUp = "KPA";
        this.unitResult = (b * 10).toString();
      } else if (a == 1) {
        this.unitDown = "KPA";
        this.unitUp = "水柱";
        this.unitResult = (b / 10).toString();
      }
    } else {
      this.unitResult = "";
    }
  }

  void calculateAndUpdate() {
    Calculator.isNew = true;
    // if (text2.isEmpty) return;

    controller.forward();
  }

  Widget buildNumberItem(String text) {
    return CalculatorItem(
      activeColor: Color(0xffb0fdb0),
      width: WidgetUtil.getWidth(60),
      height: WidgetUtil.getWidth(35),
      color: MyTheme(mContext).getColor("white"),
      onTap: () => addText(text),
      child: Center(
        child: Text(
          text,
          style: TextStyle(
              fontSize: WidgetUtil.getFontSize(10),
              color: MyTheme(mContext).getColor("colorBlack"),
              fontFamily: "din_medium"),
        ),
      ),
    );
  }

  Widget buildOperateItem(String icon, String text) {
    if (Calculator.isNew) {
      String result = calculator.expressionText();
      text = result + text;
    }
    Calculator.isNew = false;
    return CalculatorItem(
      activeColor: Color(0xffb0fdb0),
      color: Colors.green,
      width: WidgetUtil.getWidth(60),
      height: WidgetUtil.getWidth(35),
      onTap: () => addText(text),
      child:Container(
        width: WidgetUtil.getWidth(60),
        height: WidgetUtil.getWidth(35),
        child: Center(
          child: ImageHelper.icon(icon, width: WidgetUtil.getWidth(10)),
        ),

      ),
    );
  }

  Widget buildDelItem() {
    return CalculatorItem(
      color: Color(0xffbdf8d2),
      activeColor: Color(0xff9bf69d),
      onTap: () => addText("<"),
      child: Center(
        child: ImageHelper.icon("ic_delete", width: WidgetUtil.getWidth(21)),
      ),
    );
  }

  Widget buildClearItem() {
    return CalculatorItem(
      onTap: () => addText("C"),
      activeColor: Color(0xffb0fdb0),
      color: Colors.white70,
      width: WidgetUtil.getWidth(60),
      height: WidgetUtil.getWidth(35),
      child: Center(
        child: Text(
          "C",
          style: TextStyle(
              color: Colors.black, fontSize: WidgetUtil.getFontSize(10)),
        ),
      ),
    );
  }

  Widget buildxItem() {
    return CalculatorItem(
      onTap: () => addText("X²"),
      activeColor: Color(0xffb0fdb0),
      color: Colors.white70,
      width: WidgetUtil.getWidth(60),
      height: WidgetUtil.getWidth(35),
      child: Center(
        child: Text(
          "x²",
          style: TextStyle(
              color: Colors.black, fontSize: WidgetUtil.getFontSize(10)),
        ),
      ),
    );
  }

  Widget buildClear2Item() {
    return CalculatorItem(
      onTap: () => addText("CE"),
      width: WidgetUtil.getWidth(60),
      height: WidgetUtil.getWidth(35),
      activeColor: Color(0xffb0fdb0),
      color: Colors.white70,
      child: Center(
        child: Text(
          "CE",
          style: TextStyle(
              color: Colors.black, fontSize: WidgetUtil.getFontSize(10)),
        ),
      ),
    );
  }

  Widget buildEqualItem() {
//     Calculator.isNew=true;
    return CalculatorItem(
      onTap: calculateAndUpdate,
      width: WidgetUtil.getWidth(60),
      height: WidgetUtil.getWidth(35),
      activeColor: Color(0xff58B0EF),
      color: Color(0xFF255585),
      child: Center(child: ImageHelper.icon("ic_equal", width: 12)),
    );
  }

  @override
  Widget build(BuildContext context) {
    WidgetUtil.init(context);
    mContext = context;
    fontLevel1 = WidgetUtil.getFontSize(38);
    fontLevel2 = WidgetUtil.getFontSize(28);
    currentFontLevel = fontLevel1;
    return Scaffold(
      backgroundColor: MyTheme(context).getColor("bg"),
      body: Stack(
        children: <Widget>[
//          计算公式上，6*6
          Positioned(
            top: 100,
            right: unitDown == "" ? 5 : 30,
            child: Container(
                height: 70,
                child: Center(
                  child: Text(
                    text1,
                    style: TextStyle(
                        fontSize: font1,
                        color:MyTheme(mContext).getColor("colorBlack"),
                        fontFamily: "din_medium"),
                  ),
                )),
          ),
          Positioned(
              top: 120,
              right: 5,
              child: Container(
                  height: 50,
                  child: Center(
                    child: Text(
                      this.unitDown,
                    ),
                  ))),
          Positioned(
            top: 50,
            left: 10,
            child: Container(
                height: 70,
                child: DropdownButtonHideUnderline(
                  child: DropdownButton(
                    value: _dvalue,
                    items: [
                      DropdownMenuItem(
                          onTap: () {
                            exchangeAction("标准");
                          },
                          child:
                              Text("标准", style: TextStyle(color: Colors.green)),
                          value: "标准"),
                      DropdownMenuItem(
                          onTap: () {
                            exchangeAction("体积");
                          },
                          child:
                              Text("体积", style: TextStyle(color: Colors.green)),
                          value: "体积"),
                      DropdownMenuItem(
                          onTap: () {
                            exchangeAction("重量");
                          },
                          child:
                              Text("重量", style: TextStyle(color: Colors.green)),
                          value: "重量"),
                      DropdownMenuItem(
                          onTap: () {
                            exchangeAction("热量");
                          },
                          child:
                              Text("热量", style: TextStyle(color: Colors.green)),
                          value: "热量"),
                      DropdownMenuItem(
                          onTap: () {
                            exchangeAction("压力");
                          },
                          child:
                              Text("压力", style: TextStyle(color: Colors.green)),
                          value: "压力"),
                    ],
                    onChanged: (value) {
                      _dvalue = value;
                      setState(() {});
                    },
                  ),
                )),
          ),
          Positioned(
              top: 50,
              right: 50,
              child: Container(
                  height: 50,
                  child: Center(
                    child: Text(
                      this.unitResult,
                      style: TextStyle(fontSize: 30),
                    ),
                  ))),
          Positioned(
              top: 50,
              right: 5,
              child: Container(
                  height: 50,
                  child: Center(
                    child: Text(
                      this.unitUp,
                    ),
                  ))),
          Positioned(
//            计算公式下，结果
              top: top2,
              right: 5,
              child: Offstage(
                offstage: hideFont2,
                child: Container(
                    height: 50,
                    child: Center(
                      child: Text(
                        text2,
                        style: TextStyle(
                            fontSize: font2,
                            color: const Color(0xffCCCCCC),
                            fontFamily: "din_medium"),
                      ),
                    )),
              )),

          Positioned(
            bottom: 0,
            left: 0.0,
            right: 0.0,
            child: Container(
              padding: EdgeInsets.only(bottom: WidgetUtil.getWidth(20)),
              child: Column(
                children: <Widget>[
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      buildClearItem(),
                      buildClear2Item(),
                      buildxItem(),
                      // buildDelItem(),
                      buildOperateItem("ic_opt_add", "+"),
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      buildNumberItem("7"),
                      buildNumberItem("8"),
                      buildNumberItem("9"),
                      buildOperateItem("ic_opt_sub", "-")
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      buildNumberItem("4"),
                      buildNumberItem("5"),
                      buildNumberItem("6"),
                      buildOperateItem("ic_opt_mul", "×"),
                      // buildOperateItem("ic_opt_div", "÷")
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      buildNumberItem("1"),
                      buildNumberItem("2"),
                      buildNumberItem("3"),
                      buildOperateItem("ic_opt_div", "÷")
                      // buildEqualItem()
                    ],
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: <Widget>[
                      buildNumberItem("√"),
                      buildNumberItem("0"),
                      buildNumberItem("."),
                      buildEqualItem()
                      // buildEqualItem()
                    ],
                  )
                ],
              ),
            ),
          ),
        ],
      ),
    );
  }

  void exchangeAction(String dvalue) {
    setState(() {
      switch (dvalue) {
        case "标准":
          print("ceshishishi");
          this.unitDown = "";
          this.unitUp = "";
          this.unitResult = "";
          break;
        case "体积":
          volum();
          break;
        case "重量":
          weight();
          break;
        case "热量":
          hot();
          break;
        case "压力":
          press();
          break;
      }
    });
  }
}
